package com.dreamoo.service.strategy.login;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dreamoo.bloomFilter.UserBloomFilter;
import com.dreamoo.common.enums.LoginType;
import com.dreamoo.common.exception.BusinessException;
import com.dreamoo.common.pojo.dto.UserLoginDTO;
import com.dreamoo.common.pojo.entity.User;
import com.dreamoo.common.pojo.vo.UserLoginVO;
import com.dreamoo.common.result.ResultCode;
import com.dreamoo.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author 山顶洞人郑某
 * @className PassWordLogin.java 密码登录
 * @date 2025 05 08
 */
@Component
public class PassWordLogin implements UserLoginStrategy {


    @Autowired
    private UserBloomFilter userBloomFilter;

    @Autowired
    private UserMapper userMapper;
    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO userLogin(UserLoginDTO userLoginDTO) {

        if (StrUtil.isEmpty(userLoginDTO.getUserName()) || StrUtil.isEmpty(userLoginDTO.getPassWord())) {
            throw new BusinessException("请输入用户名和密码");
        }
        //利用布隆过滤器判断用户是否存在
        if (BooleanUtil.isTrue(userBloomFilter.contains(userLoginDTO.getUserName()))) {
            //再次查询数据库
         User user =  userMapper.selectOne(userLoginDTO.getUserName(), userLoginDTO.getPassWord());
         if (Optional.ofNullable(user).isPresent()) {
             UserLoginVO userLoginVO = new UserLoginVO();
             BeanUtils.copyProperties(user,userLoginVO);
             return userLoginVO;
         }
        }
        throw new BusinessException(ResultCode.USER_NOT_FOUND);
    }

    @Override
    public LoginType loginType() {
        return LoginType.PASS_WORD_LOGIN;
    }
}
